#pragma once
#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <unistd.h>
#include "Log.hpp"
#include "commd.hpp"
#include "nocopy.hpp"
#include "InetAddr.hpp"
using namespace std;


class UdpServer : public nocopy {
public :
    UdpServer(const uint16_t port) 
        :_port(port)
    {

    }
    void Init() {
        // 1、创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0) {
            // 创建套接字失败
            lg.LogMessage(Fatal, "create socket error, error code: %d, error string: %s", errno, strerror(errno));
            exit(Socket_Err);
        }
        // 创建套接字成功
        lg.LogMessage(Debug, "create socket success, sockfd: %d", _sockfd);

        // 2、绑定

        // 先填充本地网络信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        // 绑定
        int n = ::bind(_sockfd, (struct sockaddr*)&local, sizeof local);
        if (n != 0) {
            // 绑定失败
            lg.LogMessage(Fatal, "bind error, error code: %d, error string: %s", errno, strerror(errno));
            exit(Bind_Err);
        }
        // 绑定成功
        lg.LogMessage(Debug, "bind sucess");
    }
    
    void Start() {
        char buffer[1024];
        struct sockaddr_in peer; // 接收客户端信息
        memset(&peer, 0, sizeof peer);
        socklen_t len = sizeof peer; 
        while (true) {
            // 先接收消息
            int n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
            if (n > 0) {
                buffer[n] = '\0';
                InetAddr addr(peer);
                cout << addr.get_info() << "# " << buffer << endl;

                // 回发消息
                string server_echo = "server echo# ";
                server_echo += buffer;
                int m = sendto(_sockfd, server_echo.c_str(), server_echo.size(), 0, (struct sockaddr*)&peer, sizeof peer);
                if (m == -1) {
                    // 发送失败
                    break;
                }
            } else {
                break;
            }

        }

    }
    ~UdpServer() {

    }
private :
    int _sockfd;
    uint16_t _port;
};